//
//  JDAuthenticationListViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2025/1/10.
//

import UIKit
import ProgressHUD
// 实名认证列表
class JDAuthenticationListViewController: JDBaseViewController {

    var isFromShopcar: Bool = false
    
    var bottomContainerView: UIView?
    var addButton: UIButton?
    
    var myTableView: UITableView?
    
    var userIsEditing = false
    var deleteSelectedIndex = -1
    var currentSelectedAuthenticationInfoIndex = -1
    var authenticationModels: [JDAuthenticationListModel?]?
    var selectedAuthenticationInfoCompeletd:((JDAuthenticationListModel?)->())?
        
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupConfig()
        self.setupUIElements()
        self.getNetData()
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        self.setupLeftBackItem()
        self.setupNavigationTitle("身份认证管理")
        if self.isFromShopcar {
//            self.customTextRightBarButtonItem("确定", #selector(confirmSelectedAuthenticationInfo), self)
        } else {
            self.customTextRightBarButtonItem("管理", #selector(editAuthenticationAction), self)
        }
    }
    
    @objc func navigationCancelAction() {
        print("取消吧")
        self.userIsEditing = false
        self.addButton?.setTitle("添加身份认证", for: .normal)
        self.customTextRightBarButtonItem("管理", #selector(editAuthenticationAction), self)
        self.myTableView?.reloadData()
    }
    
    @objc func confirmSelectedAuthenticationInfo() {
        if self.currentSelectedAuthenticationInfoIndex >= 0 && self.currentSelectedAuthenticationInfoIndex < (self.authenticationModels?.count ?? 0) {
            let currentModel = self.authenticationModels?[self.currentSelectedAuthenticationInfoIndex]
            self.selectedAuthenticationInfoCompeletd?(currentModel)
            self.navigationController?.popViewController(animated: true)
        } else {
            self.view.toast(message: "请选择身份认证信息")
        }
    }
    
    @objc func editAuthenticationAction() {
        if self.userIsEditing {
            
        } else {
            
        }
        self.userIsEditing = true
        self.addButton?.setTitle("删除", for: .normal)
        self.customTextRightBarButtonItem("取消", #selector(navigationCancelAction), self)
        self.myTableView?.reloadData()
    }
    
    
    
    func setupUIElements() {
        
        self.bottomContainerView = UIView()
        self.view.addSubview(self.bottomContainerView!)
        self.bottomContainerView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(102)
        })
        self.bottomContainerView?.backgroundColor = .white
        
        self.addButton = UIButton(type: .custom)
        self.bottomContainerView?.addSubview(self.addButton!)
        self.addButton?.snp.makeConstraints({ make in
            make.left.equalTo(self.bottomContainerView!).offset(12)
            make.right.equalTo(self.bottomContainerView!).offset(-12)
//            make.centerY.equalTo(self.bottomContainerView!)
            make.top.equalTo(self.bottomContainerView!).offset(17)
            make.height.equalTo(54)
        })
        self.addButton?.layer.cornerRadius = 27
        self.addButton?.backgroundColor = color("#FA6161")
        self.addButton?.setTitle("添加身份认证", for: .normal)
        self.addButton?.setTitleColor(.white, for: .normal)
        self.addButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.addButton?.addTarget(self, action: #selector(addOrDeleteAuthenticationAction(_:)), for: .touchUpInside)
        
        self.myTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.myTableView!)
        self.myTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
            make.bottom.equalTo(self.bottomContainerView!.snp.top)
        })
        self.myTableView?.separatorStyle = .none
        self.myTableView?.delegate = self
        self.myTableView?.dataSource = self
        self.myTableView?.register(UITableViewCell.self, forCellReuseIdentifier: "myCell")
        self.myTableView?.backgroundColor = .commonColor()
        
        self.myTableView?.addRefreshHeader { [weak self] in
            self?.currentPage = 1
            self?.getNetData(true)
        }
        
        self.myTableView?.addRefreshFooter { [weak self] in
            self?.currentPage += 1
            self?.getNetData(false)
        }
        
    }
    
    /// 添加或者删除认证
    @objc func addOrDeleteAuthenticationAction(_ button: UIButton) {

        if button.currentTitle == "删除" {
            if self.deleteSelectedIndex >= 0 {
                let currentModel = self.authenticationModels?[self.deleteSelectedIndex]
                // 调用删除接口，成功后，重新获取当前页面数据
                ProgressHUD.animate()
                var params = [String: Any]()
                params["id"] = currentModel?.id
                JDNetWorkRequest(.deleteRealNameInfo(params)) { responseStr in
                    
                    printLog("接口请求成功:\(responseStr)")
                    ProgressHUD.dismiss()
                    let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                    if commonModel?.code == "0" {
                        
                        
                        self.getNetData(true)
//
//                        if let models = [JDAuthenticationListModel].deserialize(from: responseStr, designatedPath: "data.records") {
//                            
//                            if isRefresh {
//                                self.authenticationModels = models
//                            } else {
//                                self.authenticationModels?.append(contentsOf: models)
//                            }
//                        }
//                        self.myTableView?.reloadData()
//                        self.myTableView?.endRefresh()
                    } else {
                        self.view.toast(message: commonModel?.msg ?? "")
                    }
                    
                } failure: { error in
                    ProgressHUD.dismiss()
                } error: { errorCode in
                    ProgressHUD.dismiss()
                }

            } else {
                self.view.toast(message: "请选择想要删除的认证信息")
            }
        } else {
            print("添加身份认证")

            let newAuthenticationView = JDNewAuthenticationView()
            newAuthenticationView.confirmButtonSelected = { [weak self] _,_ in
                // 认证完成之后的操作
                self?.getNetData()
            }
            JDTools.getKeyWindows()?.rootViewController?.view.addSubview(newAuthenticationView)
            
        }
    }
    
    override func getNetData(_ isRefresh: Bool = true) {
        var params = [String: Any]()
        params["pageNumber"] = self.currentPage
        params["pageSize"] = "10"
        
        self.showLoading()
        JDNetWorkRequest(.pageRealNameIdentificationInfo(params)) { responseStr in
            printLog("接口请求成功:\(responseStr)")
            self.dismissLoading()
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                if let models = [JDAuthenticationListModel].deserialize(from: responseStr, designatedPath: "data.records") {
                    
                    if isRefresh {
                        self.authenticationModels = models
                    } else {
                        self.authenticationModels?.append(contentsOf: models)
                    }
                }
                self.myTableView?.reloadData()
                self.myTableView?.endRefresh()
            }
        } failure: { error in
            self.myTableView?.endRefresh()
            self.dismissLoading()
        } error: { errorCode in
            self.myTableView?.endRefresh()
            self.dismissLoading()
        }

    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    @objc func deleteButtonAction(_ button: UIButton) {
        
        if self.deleteSelectedIndex == button.tag {
            self.deleteSelectedIndex = -1
        } else {
            self.deleteSelectedIndex = button.tag
        }
        self.myTableView?.reloadData()
        
    }

}

extension JDAuthenticationListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.authenticationModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell")
        
        for subV in cell?.contentView.subviews ?? [UIView]() {
            subV.removeFromSuperview()
        }
        cell?.contentView.backgroundColor = .commonColor()

        
        let currentModel = self.authenticationModels?[indexPath.row]
        
        let containerView = UIView()
        cell?.contentView.addSubview(containerView)
        
        if self.userIsEditing {
            let editButton = UIButton(type: .custom)
            cell?.contentView.addSubview(editButton)
            editButton.snp.makeConstraints { make in
                make.left.equalTo(cell!.contentView).offset(12)
                make.centerY.equalTo(cell!.contentView)
                make.size.equalTo(CGSizeMake(22, 22))
            }
            if self.deleteSelectedIndex == indexPath.row {
                editButton.setImage(UIImage(named: "authentication_deleted")?.withRenderingMode(.alwaysOriginal), for: .normal)
            } else {
                editButton.setImage(UIImage(named: "authentication_unDeleted")?.withRenderingMode(.alwaysOriginal), for: .normal)
            }
            editButton.tag = indexPath.row
            editButton.addTarget(self, action: #selector(deleteButtonAction(_:)), for: .touchUpInside)
            
            containerView.snp.makeConstraints { make in
                make.left.equalTo(editButton.snp.right).offset(18)
                make.right.equalTo(cell!.contentView).offset(-12)
                make.top.equalTo(cell!.contentView).offset(10)
                make.bottom.equalTo(cell!.contentView)
            }
            
        } else {
            containerView.snp.makeConstraints { make in
                make.left.equalTo(cell!.contentView).offset(12)
                make.right.equalTo(cell!.contentView).offset(-12)
                make.top.equalTo(cell!.contentView).offset(10)
                make.bottom.equalTo(cell!.contentView)
            }
        }
        
        containerView.backgroundColor = .white
        containerView.makeCorner(8)
        
        
        
        let realNameLabel = UILabel()
        containerView.addSubview(realNameLabel)
        realNameLabel.snp.makeConstraints({ make in
            make.left.equalTo(containerView).offset(12)
            make.top.equalTo(containerView).offset(20)
            make.height.equalTo(22)
        })
        realNameLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        realNameLabel.text = currentModel?.realName
        
        
        let authenticationImageV = UIImageView()
        containerView.addSubview(authenticationImageV)
        authenticationImageV.snp.makeConstraints({ make in
            make.left.equalTo(realNameLabel.snp.right).offset(6)
            make.centerY.equalTo(realNameLabel)
            make.size.equalTo(CGSizeMake(50, 16))
        })
        authenticationImageV.image = UIImage(named: "authentication_ok")?.withRenderingMode(.alwaysOriginal)

        let buyerIdCard = UILabel()
        containerView.addSubview(buyerIdCard)
        buyerIdCard.snp.makeConstraints({ make in
            make.left.equalTo(containerView).offset(12)
            make.top.equalTo(realNameLabel.snp.bottom).offset(4)
            make.height.equalTo(20)
            make.bottom.equalTo(containerView).offset(-16)
        })
        buyerIdCard.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#8D9198"), numberOfLines: 1)
        buyerIdCard.text = currentModel?.idCardNo
        
        
        if self.isFromShopcar {
            
            let selectedImgV = UIImageView()
            containerView.addSubview(selectedImgV)
            selectedImgV.snp.makeConstraints { make in
                make.top.right.equalTo(containerView)
                make.size.equalTo(CGSizeMake(16, 16))
            }
            selectedImgV.image = UIImage(named: "authentication_selected")?.withRenderingMode(.alwaysOriginal)
            
             
            if self.currentSelectedAuthenticationInfoIndex == indexPath.row  {
                selectedImgV.isHidden = false
            } else {
                selectedImgV.isHidden = true
            }
        }

        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 82+10
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if self.isFromShopcar {
//            if self.currentSelectedAuthenticationInfoIndex == indexPath.row {
//                self.currentSelectedAuthenticationInfoIndex = -1
//            } else {
//                self.currentSelectedAuthenticationInfoIndex = indexPath.row
//            }
//            self.myTableView?.reloadData()
            // MARK: 如果点击后，需要二次确认，展开上面的代码，删除掉下面的代码，并展示右上角的按钮
            let currentModel = self.authenticationModels?[indexPath.row]
            self.selectedAuthenticationInfoCompeletd?(currentModel)
            self.navigationController?.popViewController(animated: true)
        }
        
        print("选择的这个")
    }
//    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
//        return true
//    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // 删除
            print("删除\(indexPath.row)项")
        } else if editingStyle == .insert {
            // 插入
        }
    }
    
    
//    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
//        let deleteAction = UIContextualAction(style: .destructive, title: "毁灭吧") { _, _, completion in
////            tableView.beginUpdates()
////            self.viewModel.remove(atIndex: indexPath.row)
////            tableView.deleteRows(at: [indexPath], with: .fade)
////            tableView.endUpdates()
//            self.view.toast(message: "毁灭吧")
//            completion(true)
//        }
//        deleteAction.image = UIImage(named: "trash-can") // 设置操作图标
//        deleteAction.backgroundColor = .blue
//        let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
//        return configuration
//    }

    
}
